package com.aim.common.aop;

import com.aim.common.annotion.Permission;
import com.aim.common.handler.log.LogManager;
import com.aim.common.handler.log.factory.LogTaskFactory;
import com.aim.config.shiro.PermissionCheckService;
import com.aim.config.shiro.ShiroKit;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.naming.NoPermissionException;
import java.lang.reflect.Method;

/**
 * @AUTO 权限检查的AOP
 * @Author AIM
 * @DATE 2019/5/9
 */
@Aspect
@Component
@Order(200)
public class PermissionAop {

    @Autowired
    private PermissionCheckService check;

    @Pointcut(value = "@annotation(com.aim.common.annotion.Permission)")
    private void cutPermission() {
    }

    @Around("cutPermission()")
    public Object doPermission(ProceedingJoinPoint point) throws Throwable {
        MethodSignature ms = (MethodSignature) point.getSignature();
        Method method = ms.getMethod();
        Permission permission = method.getAnnotation(Permission.class);
        Object[] permissions = permission.value();
        if (permissions.length == 0) {
            if (check.checkAll()) {//检查全体角色
                return point.proceed();
            } else {
                LogManager.me().execLog(LogTaskFactory.excpLog(ShiroKit.getUserId(), ms.getDeclaringTypeName(), ms.getName(), "没有访问权限!!"));
                throw new NoPermissionException("没有访问权限!!");
            }
        } else {
            if (check.check(permissions)) {//检查指定角色
                return point.proceed();
            } else {
                LogManager.me().execLog(LogTaskFactory.excpLog(ShiroKit.getUserId(), ms.getDeclaringTypeName(), ms.getName(), "没有访问权限!!"));
                throw new NoPermissionException("没有访问权限!!");
            }
        }
    }
}
